package org.sundatagroup.aurora.show.entity.asset;

import java.io.Serializable;

import org.sundatagroup.aurora.show.entity.model.AssetModel;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

/**
 * 图片资源
 * @author Zdream
 * @date 2018-04-24
 * @version 0.1.1
 * @see AssetType#IMAGE
 */
public class ImageAsset extends Asset implements Serializable {
	
	private static final long serialVersionUID = 8293129564896941437L;
	
	protected String path;

	public ImageAsset(String name) {
		super(name);
	}
	
	public ImageAsset() {
		this(null);
	}

	@Override
	public final AssetType type() {
		return AssetType.IMAGE;
	}

	@Override
	public JsonObject toJson() {
		JsonObject o = super.toJson();
		
		JsonObject data = new JsonObject();
		data.addProperty("path", path);
		o.add("data", data);
		
		return o;
	}
	
	/**
	 * 图片存储的路径
	 * @return
	 */
	public String getPath() {
		return path;
	}
	
	/**
	 * 设置图片存储的路径数据 (谨慎)
	 * @param pathValue
	 */
	public void setPath(String pathValue) {
		this.path = pathValue;
	}
	
	/**
	 * 将资源转化成 {@link ImageAsset} 类
	 * 要求 asset 的 type 类型必须为 {@link AssetType#IMAGE} 指定的字符串
	 * @param asset
	 * @return
	 * @throws IllegalArgumentException
	 *   当 type 类型判断不正确时
	 */
	public static ImageAsset of(AssetModel am) throws IllegalArgumentException {
		if (!AssetType.IMAGE.getName().equals(am.getType())) {
			throw new IllegalArgumentException("类型不匹配, 无法将 Asset 转成 PathAsset: type: "
					+ am.getType() + " != " + AssetType.IMAGE.getName());
		}
		
		ImageAsset a = new ImageAsset();
		
		JsonParser parser = new JsonParser();
		JsonElement je = parser.parse(am.getData());
		a.path = je.getAsJsonObject().get("path").getAsString();
		
		a.desc = am.getDesc();
		a.name = am.getName();
		a.setAid(am.getAid());
		
		return a;
	}

	@Override
	public String toString() {
		return "PathAsset [path=" + path + ", name=" + name + ", desc=" + desc + ", aid=" + getAid() + "]";
	}

}
